package com.ruoyi.ys7Video.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.ys7Video.domain.GetVideoAutoTask;
import com.ruoyi.ys7Video.domain.PresetInfo;
import com.ruoyi.ys7Video.domain.VideoAutoTask;
import com.ruoyi.ys7Video.domain.VideoDao;
import com.ruoyi.ys7Video.service.VideoAutoTaskService;
import com.ruoyi.ys7Video.service.VideoService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * @program: my-ruoyi-master_202130504106_李航
 * @description:
 * @author: LiHang
 * @create: 2022-01-10 16:10
 **/
@Api("视频定时任务处理类")
@Slf4j
@RestController
@RequestMapping("/videoAutoTask")
public class VideoAutoTaskController {

    /**
     * 获取身份令牌
     */
    @Autowired
    private TokenService tokenService;

    /**
     * 获取萤石云 key
     */
    @Value("${ys7.ys7AppKey}")
    private String ys7AppKey;

    /**
     * 获取萤石云密钥
     */
    @Value("${ys7.ys7AppSecret}")
    private String ys7AppSecret;

    /**
     * 萤石云 Token Url
     */
    @Value("${ys7.ys7tokenUrl}")
    private String ys7tokenUrl;

    /**
     * 萤石云 获取-播放地址 Url
     */
    @Value("${ys7.ys7LiveAddress}")
    private String ys7LiveAddress;

    /**
     * 萤石云 抓拍图片地址
     */
    @Value("${ys7.ys7CaptureUrl}")
    private String ys7CaptureUrl;

    /**
     * 萤石云 添加预置位
     */
    @Value("${ysOperation.ys7PresetAdd}")
    private String ys7PresetAdd;

    /**
     * 萤石云 调用预置位
     */
    @Value("${ysOperation.ys7PresetMove}")
    private String ys7PresetMove;


    /**
     * 萤石云 清除预置位
     */
    @Value("${ysOperation.ys7PresetClear}")
    private String ys7PresetClear;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * service
     */
    @Autowired
    private VideoService videoService;

    /**
     * service
     */
    @Autowired
    private VideoAutoTaskService videoAutoTaskService;

    @ApiOperation("查看所有定时任务")
    @GetMapping("/selectAllTask")
    public AjaxResult selectAllTask(){
        return AjaxResult.success(videoAutoTaskService.selectAllTask());
    }

    @ApiOperation("根据设备序列号查看所有定时任务")
    @GetMapping("/selectAllTaskBydeviceSerial")
    public AjaxResult selectAllTaskBydeviceSerial(VideoAutoTask videoAutoTask){
        return AjaxResult.success(videoAutoTaskService.selectAllTaskBydeviceSerial(videoAutoTask));
    }

    @ApiOperation("开始自动任务")
    @PostMapping("/startTask")
    public AjaxResult startTask(GetVideoAutoTask getVideoAutoTask) {
        String cron="";
        VideoAutoTask videoAutoTask = new VideoAutoTask();
        if(getVideoAutoTask.getIsEachHour()==1){
            cron=getVideoAutoTask.getSecond().toString()+" "+getVideoAutoTask.getMinute().toString()+"  * * * ?";
        }else {
            cron=getVideoAutoTask.getSecond().toString()+" "+getVideoAutoTask.getMinute().toString()+" "+getVideoAutoTask.getHour().toString()+ " * * ?";
        }
        if(getVideoAutoTask.getIsNowPreset()==1){
            PresetInfo presetInfo = new PresetInfo();
            presetInfo.setDeviceSerial(getVideoAutoTask.getDeviceSerial());
            presetInfo.setRemark(getVideoAutoTask.getRemark());
            VideoDao videoDao = videoService.selectVideoLast();
            log.info("---------->" + videoDao.toString());
//        String getLiveAddressUrl = ys7LiveAddress + "?accessToken=" + videoDao.getAccessToken() + "&deviceSerial=" + videoDao.getDeviceSerial();
            String getLiveAddressUrl = ys7PresetAdd + "?accessToken=" + videoDao.getAccessToken() + "&deviceSerial=" + presetInfo.getDeviceSerial()+"&channelNo=1";
            log.info(getLiveAddressUrl);
            try {
                ResponseEntity<String> responseEntity = Threads.postRequest(getLiveAddressUrl);
                /* 拿到data数据 */
                JSONObject jsonObject = JSONObject.parseObject(responseEntity.getBody());
                String code=jsonObject.get("code").toString();
                if(code.equals("60008")){
                    return AjaxResult.error("添加的预置点个数达到上限（12个），请清除不需要的预置点后在进行添加操作");
                }else if(code.equals("200")) {
                    Integer nowIndex = Integer.valueOf(jsonObject.getJSONObject("data").get("index").toString());
                    log.info(String.valueOf(nowIndex));
                    presetInfo.setIndexId(nowIndex);
                    videoService.insertPreset(presetInfo);

                    videoAutoTask.setPresetIndexId(nowIndex);
                    videoAutoTask.setDeviceSerial(getVideoAutoTask.getDeviceSerial());
                    videoAutoTask.setCron(cron);
                    int id = videoAutoTaskService.insertAutoTask(videoAutoTask);
                    return AjaxResult.success(id);
                }else {
                    return AjaxResult.error("未知错误，请联系管理员，错误码："+code);
                }
            } catch (Exception e) {
                System.out.println(e);
                return AjaxResult.error("添加预置位出错！请重试!");
            }
        }else {
            videoAutoTask.setPresetIndexId(getVideoAutoTask.getIndexId());
            videoAutoTask.setDeviceSerial(getVideoAutoTask.getDeviceSerial());
            videoAutoTask.setCron(cron);
            int id = videoAutoTaskService.insertAutoTask(videoAutoTask);
            return AjaxResult.success(id);
        }
    }

    /**
     * 根据id关闭任务
     **/
    @GetMapping("/stopTask")
    public AjaxResult stopCron(Integer id) {

        videoAutoTaskService.deleteAutoTask(id);
        return AjaxResult.success(id);
    }

    /**
     * 修改自动任务
     **/
    @PostMapping("/changeTask")
    public AjaxResult changeTask(GetVideoAutoTask getVideoAutoTask) {
        videoAutoTaskService.deleteAutoTask(getVideoAutoTask.getId());
        String cron="";
        VideoAutoTask videoAutoTask = new VideoAutoTask();
        if(getVideoAutoTask.getIsEachHour()==1){
            cron=getVideoAutoTask.getSecond().toString()+" "+getVideoAutoTask.getMinute().toString()+"  * * * ?";
        }else {
            cron=getVideoAutoTask.getSecond().toString()+" "+getVideoAutoTask.getMinute().toString()+" "+getVideoAutoTask.getHour().toString()+ " * * ?";
        }
        videoAutoTask.setPresetIndexId(getVideoAutoTask.getIndexId());
        videoAutoTask.setDeviceSerial(getVideoAutoTask.getDeviceSerial());
        videoAutoTask.setCron(cron);
        int id = videoAutoTaskService.insertAutoTask(videoAutoTask);
        return AjaxResult.success(id);
    }
}
